import request from "./request.js"
const $http = new request();
// 心跳配置

const heartbeat = {
	timeout: 6000,
	timeouter: {},
	checkStatus: () => {
		heartbeat.timeouter && clearInterval(heartbeat.timeouter);
		heartbeat.timeouter = setInterval(() => {
			uni.sendSocketMessage({
				data: JSON.stringify({
					type: 'ping'
				})
			});
		}, heartbeat.timeout);
	}
}


export default class Zsockets {
	constructor() {}
	// 注意事项：需要注意时序，有许多的生命周期都需要在连接之后才能调用
	async connets() {
		uni.closeSocket();
		const user = uni.getStorageSync('userInfos');
		uni.showLoading({
			title: "正在连接中~"
		});
		await this.close();
		return new Promise(resolve => {
			uni.connectSocket({
				url: "ws://121.89.218.65:7272",
				success: (e) => {
					uni.showToast({
						title: "连接已恢复！",
						icon: "none"
					})

					uni.onSocketMessage(async (e) => {
						const ress = JSON.parse(e.data);
						// console.log("server信息：", ress);
						if (ress.type == 'bind') {
							getApp().globalData.client_id = ress.data.client_id
							if (user) {
								console.log(ress.data.client_id);
								// 绑定ws
								const res2 = await $http.Request(
									'user.worker/bind', {
										client_id: ress.data.client_id
									});
							}
						}
						heartbeat.checkStatus();
						const pages = getCurrentPages();
						const data = JSON.parse(e.data);
						const page = pages[pages.length - 1].$vm;
						try {
							page.onGetMessage(ress);
						} catch (E) {}
					});
					getApp().globalData.socketStatus = 1;
					resolve(true);
				},
				fail: (err) => {
					console.log(err);
					uni.showModal({
						content: err,
						showCancel: false
					})
					resolve(false);
				},
				complete: () => {
					uni.hideLoading();
				}
			});
			// uni.onSocketOpen(function(res) {
			// 	console.log('WebSocket连接已打开！');
			// 	resolve();
			// 	uni.showToast({
			// 		title: "连接已恢复！",
			// 		icon: "none"
			// 	})
			// });
		})


		uni.onSocketError(function(res) {
			getApp().globalData.socketStatus = 0;
			console.log('WebSocket连接打开失败，请检查！');
		});

		uni.onSocketClose(function(res) {
			console.log('WebSocket 已关闭！');
			getApp().globalData.socketStatus = 0;
			clearInterval(heartbeat.timeouter);
			uni.showToast({
				title: "连接已断开！",
				icon: "none"
			})
		});

	};
	/**
	 * @param {Object} methodname 方法名
	 * @param {Object} data 数据
	 */
	sendMsg(methodname, data = {}) {
		data.methodname = methodname;
		data = JSON.stringify(data);
		return new Promise(resolve => {
			uni.sendSocketMessage({
				data: data,
				success: (e) => {
					resolve(e)
				},
				fail(err) {
					console.log(err);
				}
			});
		})

	};
	close() {
		try {
			return Promise(resolve => {
				uni.closeSocket({
					complete: () => {
						resolve()
					}
				})
			})
		} catch (e) {}
	}
}
